#ifndef CONFIGMANAGER_H
#define CONFIGMANAGER_H

#include <QCoreApplication>
#include <QDir>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QFileInfo>
#include <QVariant>
#include <QTextStream>
#include <QMap>
#include "pathmanager.h"

class SecureTokenManager;

class ConfigManager
{
private:
    static QJsonObject s_config;
    static QString s_configPath;
    static bool s_loaded;

public:
    static void initialize()
    {
        if (!s_loaded) {
            // 使用PathManager获取标准配置目录
            QString configDir = PathManager::getConfigDirectory();
            PathManager::ensureDirectoryExists(configDir);
            s_configPath = QDir(configDir).absoluteFilePath("config.json");
            loadConfig();
            s_loaded = true;
        }
    }
    
    static void loadConfig()
    {
        QFile file(s_configPath);
        if (file.exists() && file.open(QIODevice::ReadOnly)) {
            QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
            s_config = doc.object();
        } else {
            s_config = createDefaultConfig();
        }
    }
    
    static QJsonObject createDefaultConfig()
    {
        QJsonObject config;

        // 应用设置
        QJsonObject app;
        app["language"] = "zh_CN";
        app["defaultPreset"] = "标准文档";
        config["app"] = app;

        // 视图设置
        QJsonObject view;
        view["zoomLevel"] = 1.0;
        view["autoApplyDefaultZoom"] = true;
        config["view"] = view;

        // 缓存设置
        QJsonObject cache;
        cache["dpiBuckets"] = "1123,1404,1754,2339,3508,7016";
        config["cache"] = cache;

        // 输出设置
        QJsonObject output;
        output["settings"] = "";
        config["output"] = output;

        // 处理设置
        QJsonObject processing;
        processing["settings"] = "";
        config["processing"] = processing;

        // 用户登录设置
        QJsonObject user;
        user["apiBase"] = "https://ctdy123.com/api/auth/client/login";
        user["deviceName"] = "";
        user["email"] = "";
        user["token"] = "";
        user["rememberEmail"] = false;
        user["rememberPassword"] = false;
        user["encryptedPassword"] = "";
        config["user"] = user;

        // 更新设置
        QJsonObject update;
        update["currentVersion"] = "2.7.2";
        update["lastCheckTime"] = "";
        update["skippedVersion"] = "";
        update["autoCheck"] = true;
        update["downloadPath"] = "";
        update["downloadState"] = QJsonObject();
        config["update"] = update;

        return config;
    }
    
    static void saveConfig()
    {
        QDir().mkpath(QFileInfo(s_configPath).absolutePath()); // 只创建父目录，不创建文件本身
        QFile file(s_configPath);
        if (file.open(QIODevice::WriteOnly)) {
            // 添加token保存前的调试信息
            if (s_config.contains("user")) {
                QJsonObject userObj = s_config["user"].toObject();
                QString authToken = userObj["authToken"].toString();
                QString userToken = userObj["token"].toString();
                QString email = userObj["email"].toString();
            }

            QJsonDocument doc(s_config);
            file.write(doc.toJson(QJsonDocument::Indented)); // 使用缩进格式
        } else {
        }
    }
    
    // 应用设置
    static void setLanguage(const QString& language) { setNestedValue("app", "language", language); }
    static QString getLanguage() { return getNestedValue("app", "language", "zh_CN").toString(); }
    
    static void setDefaultPreset(const QString& preset) { setNestedValue("app", "defaultPreset", preset); }
    static QString getDefaultPreset() { return getNestedValue("app", "defaultPreset", "标准文档").toString(); }
    
    // 窗口设置
    static void setGeometry(const QByteArray& geometry) { setNestedValue("window", "geometry", QString(geometry.toBase64())); }
    static QByteArray getGeometry() { return QByteArray::fromBase64(getNestedValue("window", "geometry", "").toString().toUtf8()); }
    
    static void setDockWidgetState(const QByteArray& state) { setNestedValue("window", "dockWidgetState", QString(state.toBase64())); }
    static QByteArray getDockWidgetState() { return QByteArray::fromBase64(getNestedValue("window", "dockWidgetState", "").toString().toUtf8()); }
    
    // 完全独立的停靠窗口状态管理
    static void setFileBrowserVisible(bool visible) { setNestedValue("window", "fileBrowserVisible", visible); }
    static bool getFileBrowserVisible() { return getNestedValue("window", "fileBrowserVisible", false).toBool(); }
    
    static void setThumbnailVisible(bool visible) { setNestedValue("window", "thumbnailVisible", visible); }
    static bool getThumbnailVisible() { return getNestedValue("window", "thumbnailVisible", false).toBool(); }
    
    // 分割条位置管理
    static void setFileBrowserWidth(int width) { setNestedValue("window", "fileBrowserWidth", width); }
    static int getFileBrowserWidth() { return getNestedValue("window", "fileBrowserWidth", 300).toInt(); }
    
    static void setThumbnailWidth(int width) { setNestedValue("window", "thumbnailWidth", width); }
    static int getThumbnailWidth() { return getNestedValue("window", "thumbnailWidth", 220).toInt(); }
    
    // 视图设置
    static void setZoomLevel(double level) { setNestedValue("view", "zoomLevel", level); }
    static double getZoomLevel() { return getNestedValue("view", "zoomLevel", 1.0).toDouble(); }
    
    // 缓存设置
    static void setDpiBuckets(const QString& buckets) { setNestedValue("cache", "dpiBuckets", buckets); }
    static QString getDpiBuckets() { return getNestedValue("cache", "dpiBuckets", "1123,1404,1754,2339,3508,7016").toString(); }
    
    // 输出设置
    static void setOutputSettings(const QString& settings) { setNestedValue("output", "settings", settings); }
    static QString getOutputSettings() { return getNestedValue("output", "settings", "").toString(); }
    
    // 处理设置
    static void setProcessingSettings(const QString& settings) { setNestedValue("processing", "settings", settings); }
    static QString getProcessingSettings() { return getNestedValue("processing", "settings", "").toString(); }

    // === 用户登录配置 ===
    // API配置
    static void setApiBase(const QString& apiBase) { setNestedValue("user", "apiBase", apiBase); }
    static QString getApiBase() { return getNestedValue("user", "apiBase", "https://ctdy123.com/api/auth/client/login").toString(); }

    // 设备信息
    static void setDeviceName(const QString& deviceName) { setNestedValue("user", "deviceName", deviceName); }
    static QString getDeviceName() { return getNestedValue("user", "deviceName", "").toString(); }

    // 用户认证信息
    static void setUserEmail(const QString& email) { setNestedValue("user", "email", email); }
    static QString getUserEmail() { return getNestedValue("user", "email", "").toString(); }

    // === 安全Token管理 ===
    // 向后兼容的Token方法（使用安全加密存储）
    static void setUserToken(const QString& token);
    static QString getUserToken();

    // 新API规范Token管理（使用安全加密存储）
    static void setAuthToken(const QString& token);
    static QString getAuthToken();

    // 安全Token专用方法
    static void setSecureToken(const QString& token, const QString& email = QString());
    static QString getSecureToken(const QString& email = QString());
    static void clearSecureToken(const QString& email = QString());
    static bool isSecureTokenValid(const QString& email = QString());
    static qint64 getSecureTokenRemainingTime(const QString& email = QString());

    // === 硬件指纹管理 ===
    static void setHardwareFingerprint(const QString& fingerprint) { setNestedValue("security", "hardwareFingerprint", fingerprint); }
    static QString getHardwareFingerprint() { return getNestedValue("security", "hardwareFingerprint", "").toString(); }

    // === 时间管理（防时间回溯攻击） ===
    static void setLastKnownTime(qint64 timestamp) { setNestedValue("security", "lastKnownTime", timestamp); }
    static qint64 getLastKnownTime() { return getNestedValue("security", "lastKnownTime", 0).toLongLong(); }

    // 订阅信息管理
    static void setSubscriptionInfo(const QJsonObject& subscription);
    static QJsonObject getSubscriptionInfo();
    static void clearSubscriptionInfo();

    // 记住选项
    static void setRememberEmail(bool remember) { setNestedValue("user", "rememberEmail", remember); }
    static bool getRememberEmail() { return getNestedValue("user", "rememberEmail", false).toBool(); }

    static void setRememberPassword(bool remember) { setNestedValue("user", "rememberPassword", remember); }
    static bool getRememberPassword() { return getNestedValue("user", "rememberPassword", false).toBool(); }

    // 加密密码存储
    static void setEncryptedPassword(const QString& encryptedPassword) { setNestedValue("user", "encryptedPassword", encryptedPassword); }
    static QString getEncryptedPassword() { return getNestedValue("user", "encryptedPassword", "").toString(); }

    // === 更新配置 ===
    // 版本管理 - 现在使用统一的版本管理系统
    static void setCurrentVersion(const QString& version) { setNestedValue("update", "currentVersion", version); }

    /**
     * @brief 获取当前版本号
     * @return 从统一版本管理系统获取的版本号
     *
     * @deprecated 请使用 LimeReader::AppVersion::getAppVersion() 替代
     * 这个方法保持向后兼容，但新代码应该使用统一的版本管理系统
     */
    static QString getCurrentVersion();

    static void setLastCheckTime(const QString& time) { setNestedValue("update", "lastCheckTime", time); }
    static QString getLastCheckTime() { return getNestedValue("update", "lastCheckTime", "").toString(); }

    static void setSkippedVersion(const QString& version) { setNestedValue("update", "skippedVersion", version); }
    static QString getSkippedVersion() { return getNestedValue("update", "skippedVersion", "").toString(); }

    // 更新设置
    static void setAutoCheck(bool enabled) { setNestedValue("update", "autoCheck", enabled); }
    static bool getAutoCheck() { return getNestedValue("update", "autoCheck", true).toBool(); }

    static void setDownloadPath(const QString& path) { setNestedValue("update", "downloadPath", path); }
    static QString getDownloadPath() { return getNestedValue("update", "downloadPath", "").toString(); }

    // 下载状态管理
    static void setDownloadState(const QJsonObject& state) { setNestedValue("update", "downloadState", state); }
    static QJsonObject getDownloadState() { return getNestedValue("update", "downloadState", QJsonObject()).toJsonObject(); }

    static void clearDownloadState() { setNestedValue("update", "downloadState", QJsonObject()); }
    
    // 通用方法
    static void setNestedValue(const QString& section, const QString& key, const QVariant& value)
    {
        initialize();
        if (!s_config.contains(section)) {
            s_config[section] = QJsonObject();
        }
        QJsonObject sectionObj = s_config[section].toObject();
        sectionObj[key] = QJsonValue::fromVariant(value);
        s_config[section] = sectionObj;
    }
    
    static QVariant getNestedValue(const QString& section, const QString& key, const QVariant& defaultValue = QVariant())
    {
        initialize();
        if (s_config.contains(section)) {
            QJsonObject sectionObj = s_config[section].toObject();
            if (sectionObj.contains(key)) {
                return sectionObj[key].toVariant();
            }
        }
        return defaultValue;
    }
    
    static bool containsNested(const QString& section, const QString& key)
    {
        initialize();
        if (s_config.contains(section)) {
            QJsonObject sectionObj = s_config[section].toObject();
            return sectionObj.contains(key);
        }
        return false;
    }

    // === 多层嵌套访问支持 ===
    // 用于API端点配置等复杂数据结构
    static QJsonArray getNestedArray(const QString& section, const QString& key)
    {
        initialize();
        if (s_config.contains(section)) {
            QJsonObject sectionObj = s_config[section].toObject();
            if (sectionObj.contains(key)) {
                return sectionObj[key].toArray();
            }
        }
        return QJsonArray();
    }

    static QJsonObject getNestedObject(const QString& section, const QString& key)
    {
        initialize();
        if (s_config.contains(section)) {
            QJsonObject sectionObj = s_config[section].toObject();
            if (sectionObj.contains(key)) {
                return sectionObj[key].toObject();
            }
        }
        return QJsonObject();
    }

    static void setNestedArray(const QString& section, const QString& key, const QJsonArray& array)
    {
        initialize();
        if (!s_config.contains(section)) {
            s_config[section] = QJsonObject();
        }
        QJsonObject sectionObj = s_config[section].toObject();
        sectionObj[key] = array;
        s_config[section] = sectionObj;
    }

    static void setNestedObject(const QString& section, const QString& key, const QJsonObject& object)
    {
        initialize();
        if (!s_config.contains(section)) {
            s_config[section] = QJsonObject();
        }
        QJsonObject sectionObj = s_config[section].toObject();
        sectionObj[key] = object;
        s_config[section] = sectionObj;
    }

    static void sync()
    {
        saveConfig();
    }

    // === 配置迁移方法 ===
    // 从user.ini迁移用户配置到config.json
    static void migrateFromUserIni()
    {
        initialize();

        QString userIniPath = QDir(QCoreApplication::applicationDirPath()).absoluteFilePath("user.ini");
        QFile userIniFile(userIniPath);

        if (!userIniFile.exists()) {
            return;
        }

        // 读取user.ini内容
        QMap<QString, QString> iniData;
        if (userIniFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&userIniFile);
            in.setEncoding(QStringConverter::Utf8);

            QString currentSection;
            while (!in.atEnd()) {
                QString line = in.readLine().trimmed();

                if (line.isEmpty() || line.startsWith(";") || line.startsWith("#")) {
                    continue;
                }

                if (line.startsWith("[") && line.endsWith("]")) {
                    currentSection = line.mid(1, line.length() - 2);
                    continue;
                }

                int equalPos = line.indexOf('=');
                if (equalPos > 0) {
                    QString key = line.left(equalPos).trimmed();
                    QString value = line.mid(equalPos + 1).trimmed();
                    iniData[key] = value;
                }
            }
            userIniFile.close();


            // 迁移用户配置到config.json
            bool hasUserData = false;

            if (iniData.contains("apiBase") && !iniData["apiBase"].isEmpty()) {
                setApiBase(iniData["apiBase"]);
                hasUserData = true;
            }

            if (iniData.contains("deviceName") && !iniData["deviceName"].isEmpty()) {
                setDeviceName(iniData["deviceName"]);
                hasUserData = true;
            }

            if (iniData.contains("email") && !iniData["email"].isEmpty()) {
                setUserEmail(iniData["email"]);
                hasUserData = true;
            }

            if (iniData.contains("token") && !iniData["token"].isEmpty()) {
                setUserToken(iniData["token"]);
                hasUserData = true;
            }

            if (iniData.contains("rememberEmail")) {
                setRememberEmail(iniData["rememberEmail"] == "1");
                hasUserData = true;
            }

            if (iniData.contains("rememberPassword")) {
                setRememberPassword(iniData["rememberPassword"] == "1");
                hasUserData = true;
            }

            if (iniData.contains("password") && !iniData["password"].isEmpty()) {
                // 直接迁移加密密码
                setEncryptedPassword(iniData["password"]);
                hasUserData = true;
            }

            if (hasUserData) {
                saveConfig();

                // 备份原user.ini文件
                QString backupPath = userIniPath + ".backup";
                if (QFile::copy(userIniPath, backupPath)) {
                }
            } else {
            }
        } else {
        }
    }
    
};

#endif // CONFIGMANAGER_H
